package com.jml.强软弱虚引用;


import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * @author:jml
 * @date: 2019/5/8 16:38
 * @description：
 */
public class 引用队列 {

    public static void main(String[] args) throws InterruptedException {
        softReference_Queue();
        //weakReference_Queue();

    }

    //-Xmx5m -Xms5m -XX:+PrintGCDetails
    private static  void softReference_Queue() throws InterruptedException {
        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue();
        SoftReference<Object> softReference = new SoftReference<>(o1,referenceQueue);
        System.out.println(o1);
        System.out.println(softReference.get());
        System.out.println(referenceQueue.poll());
        System.out.println("=======================");
        o1=null;
        System.gc();
        Thread.sleep(500);
        try {
            byte[] bytes = new byte[1024*1024*10];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(o1);
            System.out.println(softReference.get());
            System.out.println(referenceQueue.poll());
        }
    }

    private static  void weakReference_Queue() throws InterruptedException {
        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue();
        WeakReference<Object> weakReference = new WeakReference<>(o1,referenceQueue);
        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());
        System.out.println("=======================");
        o1=null;
        System.gc();
        Thread.sleep(500);
        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());
    }



}
